﻿using AutoMapper;
using DFGK.IRepository.LY;
using DFGK.IService.LY;
using DFGK_WMS.Model.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK.Service.LY
{
    public class EquipmentDataStatisticsService : BaseService, IEquipmentDataStatisticsService
    {

        private readonly IEquipmentRepository _equipmentDataStatisticsRepository;
        private readonly IEquipmentChangeRepository _equipmentChangeRepository;
        private readonly IEquipmentStatisticsRepository _equipmentStatisticsRepository;
        private readonly IUnitEquipmentRepository _unitEquipmentRepository;
        private readonly IVehicleOrganizationStatRepository _vehicleOrganizationStatRepository;
        private readonly IVehiclePurchaseRepository _vehiclePurchaseRepository;
        private readonly IVehicleStatusRepository _vehicleStatusRepository;
        private readonly IVehicleRepository _vehicleRepository;
        private readonly IRegionRepository _regionRepository;
        private readonly IOrganizationRepository _organizationRepository;
        private readonly IStatisticsRepository _statisticsRepository;

        public EquipmentDataStatisticsService(IMapper mapper, IEquipmentRepository equipmentDataStatisticsRepository, IEquipmentChangeRepository equipmentChangeRepository, IVehicleOrganizationStatRepository vehicleOrganizationStatRepository, IVehiclePurchaseRepository vehiclePurchaseRepository, IVehicleStatusRepository vehicleStatusRepository, IVehicleRepository vehicleRepository, IEquipmentStatisticsRepository equipmentStatisticsRepository, IUnitEquipmentRepository unitEquipmentRepository, IRegionRepository regionRepository, IOrganizationRepository organizationRepository, IStatisticsRepository statisticsRepository) : base(mapper)
        {
            _equipmentDataStatisticsRepository = equipmentDataStatisticsRepository;
            _equipmentChangeRepository = equipmentChangeRepository;
            _vehicleOrganizationStatRepository = vehicleOrganizationStatRepository;
            _vehiclePurchaseRepository = vehiclePurchaseRepository;
            _vehicleStatusRepository = vehicleStatusRepository;
            _vehicleRepository = vehicleRepository;
            _equipmentStatisticsRepository = equipmentStatisticsRepository;
            _unitEquipmentRepository = unitEquipmentRepository;
            _regionRepository = regionRepository;
            _organizationRepository = organizationRepository;
            _statisticsRepository = statisticsRepository;
        }


        /// <summary>
        /// 1.装备数量占比统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<EquipmentSummaryDto> GetEquipment(int pageIndex, int pageSize, out int totalCount)
        {
            // 获取所有装备的总数量
            var totalQuantity = _equipmentDataStatisticsRepository.GetEntityAlls().Sum(e => e.Quantity);

            // 按类别和名称分组，并计算每个分组的总数量和占比
            var categorySummary = _equipmentDataStatisticsRepository.GetEntityAlls()
                .GroupBy(e => new { e.EquipmentCategory, e.EquipmentName })
                .Select(g => new EquipmentSummaryDto
                {
                    Category = g.Key.EquipmentCategory,
                    EquipmentName = g.Key.EquipmentName,
                    TotalQuantity = g.Sum(e => e.Quantity),
                    // 计算占比并转化为字符串形式，并添加 "%" 符号
                    EquipmentPercentage = totalQuantity > 0
                        ? (g.Sum(e => e.Quantity) * 100.0 / totalQuantity).ToString("F2") + "%"
                        : "0%"
                })
                .ToList();

            // 获取分页数据
            var pagedList = categorySummary
                .Skip((pageIndex - 1) * pageSize)  // 计算跳过的条目数
                .Take(pageSize)  // 获取分页数据
                .ToList();

            // 设置总条数
            totalCount = categorySummary.Count;

            return pagedList;
        }
        /// <summary>
        /// 2.装备数量增减统计
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<EquipmentChangeDto> GetEquipmentChangeStatistics(
    string? equipmentType, DateTime? startDate, DateTime? endDate,
    int pageIndex, int pageSize, out int totalCount)
        {
            var query = _equipmentChangeRepository.GetEntityAlls();

            // 处理装备类型筛选
            if (!string.IsNullOrEmpty(equipmentType))
            {
                query = query.Where(e => e.EquipmentType == equipmentType);
            }

            // 处理开始日期筛选
            if (startDate != null)
            {
                query = query.Where(e => e.ChangeDate >= startDate);
            }

            // 处理结束日期筛选
            if (endDate != null)
            {
                query = query.Where(e => e.ChangeDate <= endDate);
            }

            // 查询并进行分组和聚合
            var equipmentChanges = query
                .GroupBy(e => new { e.EquipmentChangeId, e.EquipmentName, e.EquipmentType, e.ChangeDate })  // 还需要包含ChangeDate进行分组
                .Select(group => new EquipmentChangeDto
                {
                    EquipmentName = group.Key.EquipmentName,
                    EquipmentType = group.Key.EquipmentType,
                    ChangeDate = group.Key.ChangeDate,  // 添加 ChangeDate
                    TotalChange = group.Sum(e => e.ChangeQuantity)
                })
                .ToList();

            // 获取分页数据
            var pagedList = equipmentChanges
                .Skip((pageIndex - 1) * pageSize)  // 计算跳过的条目数
                .Take(pageSize)  // 获取分页数据
                .ToList();

            // 设置总条数
            totalCount = equipmentChanges.Count;  // 计算所有符合条件的记录总数

            return pagedList;  // 返回分页后的结果
        }
        /// <summary>
        /// 3.装备按组织单位统计
        /// </summary>
        /// <param name="unit"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<UnitEquipmentsDto> GetUnitEquipments(int pageIndex, int pageSize, out int totalCount)
        {
            var unitEquipments = _unitEquipmentRepository.GetEntityAlls()
     .GroupBy(ue => ue.UnitName)
     .Select(group => new
     {
         UnitName = group.Key,
         TotalQuantity = group.Sum(ue => ue.Quantity)
     }).ToList();

            // 计算总数量
            var totalQuantity = unitEquipments.Sum(ue => ue.TotalQuantity);

            // 计算每个单位的装备占比
            var unitEquipmentsWithPercentage = unitEquipments.Select(ue => new UnitEquipmentsDto
            {
                UnitName = ue.UnitName,
                TotalQuantity = ue.TotalQuantity,
                EquipmentPercentage = (int)Math.Round((double)ue.TotalQuantity / totalQuantity * 100) + "%"  // 装备占比（整数）
            }).ToList();
            // 获取分页数据
            var pagedList = unitEquipmentsWithPercentage
                    .Skip((pageIndex - 1) * pageSize)  // 计算跳过的条目数
                    .Take(pageSize)  // 获取分页数据
                    .ToList();

            // 设置总条数
            totalCount = unitEquipmentsWithPercentage.Count;
            return pagedList;
        }
        //装备大数据统计分析:
        public List<EquipmentStatisticsDto> GetEquipmentStatistics(DateTime? startDate, DateTime? endDate, int pageIndex, int pageSize, out int totalCount)
        {
            // 获取所有设备统计数据
            var equipmentAnalysisQuery = _equipmentStatisticsRepository.GetEntityAlls();

            // 日期过滤：如果 startDate 和 endDate 都有值，则过滤数据
            if (startDate.HasValue)
            {
                equipmentAnalysisQuery = equipmentAnalysisQuery.Where(es => es.StatisticsDate >= startDate.Value);
            }

            if (endDate.HasValue)
            {
                equipmentAnalysisQuery = equipmentAnalysisQuery.Where(es => es.StatisticsDate <= endDate.Value);
            }

            // 按照类别分组并求和
            var equipmentAnalysis = equipmentAnalysisQuery
                .GroupBy(es => es.Category)
                .Select(group => new EquipmentStatisticsDto
                {
                    Category = group.Key, // 类别
                    TotalQuantity = group.Sum(es => es.Quantity) // 各类别的数量总和
                }).ToList();  // 将数据加载到内存中

            // 获取总条数（不包括分页）
            totalCount = equipmentAnalysis.Count;

            // 获取分页数据
            var pagedList = equipmentAnalysis
                .Skip((pageIndex - 1) * pageSize)  // 计算跳过的条目数
                .Take(pageSize)  // 获取分页数据
                .ToList();

            return pagedList;
        }


        /// <summary>
        /// // 车辆数量占比统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<VehicleCategoryStatsDto> GetVehicleCategoryStats(int pageIndex, int pageSize, out int totalCount)
        {
            // 计算所有车辆的总数量
            var totalQuantity = _vehicleRepository.GetEntityAlls().Sum(v => v.Quantity);

            // 使用 LINQ 查询车辆类别的总数量和占比
            var categoryStats = _vehicleRepository.GetEntityAlls()
                .GroupBy(v => v.Category)  // 按类别分组
                .Select(g => new VehicleCategoryStatsDto
                {
                    Category = g.Key,  // 获取类别名称
                    TotalQuantity = g.Sum(v => v.Quantity),  // 计算每个类别的总数量
                    Percentage = (int)Math.Round(g.Sum(v => v.Quantity) / (double)totalQuantity * 100)
                })
                .ToList();
            // 获取分页数据
            var pagedList = categoryStats
                .Skip((pageIndex - 1) * pageSize)  // 计算跳过的条目数
                .Take(pageSize)  // 获取分页数据
                .ToList();

            // 设置总条数
            totalCount = categoryStats.Count;
            return categoryStats;

        }
        /// <summary>
        /// 6.车辆质量状态统计分析
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<VehicleStatusDto> GetVehicleStatusStats(int pageIndex, int pageSize, out int totalCount)
        {
            // 使用 LINQ 查询车辆的状态统计
            var statusStats = _vehicleStatusRepository.GetEntityAlls()
                .GroupBy(vs => vs.Status)  // 按状态分组
                .Select(g => new VehicleStatusDto
                {
                    Status = g.Key,  // 获取状态类型
                    Quantity = g.Count()  // 计算每个状态下的车辆数量
                })
                .ToList();

            // 获取分页数据
            var pagedList = statusStats
                .Skip((pageIndex - 1) * pageSize)  // 计算跳过的条目数
                .Take(pageSize)  // 获取分页数据
                .ToList();

            // 设置总条数
            totalCount = statusStats.Count;
            return statusStats;
        }
        /// <summary>
        /// 7.车辆按组织单位统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<VehicleOrganizationStatsDto> GetVehicleOrganizationStats(int pageIndex, int pageSize, out int totalCount)
        {
            // 计算所有车辆的总数量
            var totalQuantity = _vehicleRepository.GetEntityAlls().Sum(v => v.Quantity);

            // 使用 LINQ 查询车辆按组织单位和类别的统计
            var orgStats = _vehicleOrganizationStatRepository.GetEntityAlls()
                .GroupBy(vos => new { vos.Organization, vos.VehicleCategory })  // 按组织和车辆类别分组
                .Select(g => new VehicleOrganizationStatsDto
                {
                    Organization = g.Key.Organization,  // 获取组织单位
                    VehicleCategory = g.Key.VehicleCategory,  // 获取车辆类别
                    TotalQuantity = g.Sum(vos => vos.TotalQuantity),  // 计算每个分组的总数量
                    Percentage = (int)Math.Round(g.Sum(vos => vos.TotalQuantity) / (double)totalQuantity * 100)  // 计算占比并转换为整数  // 计算占比
                })
                .ToList();

            // 获取分页数据
            var pagedList = orgStats
                .Skip((pageIndex - 1) * pageSize)  // 计算跳过的条目数
                .Take(pageSize)  // 获取分页数据
                .ToList();

            // 设置总条数
            totalCount = orgStats.Count;
            return orgStats;
        }
        /// <summary>
        /// 8.车辆采购数据统计分析
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<VehiclePurchaseStatsDto> GetVehiclePurchaseStats(int pageIndex, int pageSize, out int totalCount, DateTime? startDate = null, DateTime? endDate = null)
        {
            // 使用 LINQ 查询车辆采购统计数据
            var purchaseStats = (from vp in _vehiclePurchaseRepository.GetEntityAlls()
                                 join v in _vehicleRepository.GetEntityAlls() on vp.VehicleId equals v.VehicleId  // 通过 VehicleId 连接车辆信息
                                 where (!startDate.HasValue || vp.PurchaseDate >= startDate)  // 过滤开始日期
                                 && (!endDate.HasValue || vp.PurchaseDate <= endDate)  // 过滤结束日期
                                 select new VehiclePurchaseStatsDto
                                 {
                                     Name = v.Name,  // 获取车辆名称
                                     PurchaseDate = vp.PurchaseDate,  // 获取采购日期
                                     Quantity = vp.Quantity,  // 获取采购数量
                                     TotalCost = vp.TotalCost  // 获取总费用
                                 }).ToList();

            // 获取分页数据
            var pagedList = purchaseStats
                .Skip((pageIndex - 1) * pageSize)  // 计算跳过的条目数
                .Take(pageSize)  // 获取分页数据
                .ToList();

            // 设置总条数
            totalCount = purchaseStats.Count;
            return pagedList;  // 返回分页后的数据
        }
        /// <summary>
        /// 组织单位地图定位统计展示
        /// </summary>
        /// <param name="regionName"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public List<OrganizationAndStatisticsDto> GetOrganizationAndStatisticsByRegion(string? regionName, DateTime? date = null)
        {
            // 查询组织单位和区域，联查区域名称
            var organizationsQuery = from o in _organizationRepository.GetEntityAlls()
                                     join r in _regionRepository.GetEntityAlls()  // 联查区域表
                                     on o.RegionId equals r.Id  // 匹配RegionId
                                     select new { o, r };  // 返回组织单位和区域

            // 如果指定了区域名称，进一步筛选组织单位（通过联查区域名称）
            if (!string.IsNullOrEmpty(regionName))
            {
                organizationsQuery = organizationsQuery.Where(x => x.r.Name == regionName);
            }

            // 获取所有符合条件的组织单位，并转化为 OrganizationDto
            var organizations = organizationsQuery
                .Select(x => new OrganizationDto
                {
                    Name = x.o.Name,
                    Latitude = (double)x.o.Latitude,
                    Longitude = (double)x.o.Longitude,
                    Address = x.o.Address
                }).ToList();

            // 查询区域统计信息
            var statisticsQuery = from a in _statisticsRepository.GetEntityAlls()  // 假设这是从统计信息表中获取数据
                                  join b in _regionRepository.GetEntityAlls()  // 匹配区域表
                                  on a.RegionId equals b.Id
                                  select new RegionStatisticsDto
                                  {
                                      RegionName = b.Name,
                                      TotalCount = a.TotalCount,
                                      Datee = a.StatisticsDate
                                  };

            // 如果指定了区域名称，筛选区域统计数据
            if (!string.IsNullOrEmpty(regionName))
            {
                statisticsQuery = statisticsQuery.Where(s => s.RegionName == regionName);
            }

            // 如果提供了日期，则按日期进一步筛选统计数据
            if (date.HasValue)
            {
                statisticsQuery = statisticsQuery.Where(s => s.Datee.Date == date.Value.Date);  // 按日期筛选
            }

            // 获取符合条件的所有统计信息
            var statistics = statisticsQuery.ToList();

            // 返回包含组织单位和区域统计信息的 DTO
            var result = new OrganizationAndStatisticsDto
            {
                Organizations = organizations,
                Statistics = statistics
            };

            return new List<OrganizationAndStatisticsDto> { result };  // 返回一个包含结果的列表
        }
        /// <summary>
        /// 库房装备数量统计分析
        /// </summary>
        /// <param name="unitName"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public List<EquipmentAnalysisDto> GetEquipmentAnalysis(DateTime? startDate = null, DateTime? endDate = null)
        {
            var query = from ue in _unitEquipmentRepository.GetEntityAlls()
                        join es in _equipmentDataStatisticsRepository.GetEntityAlls() on ue.EquipmentId equals es.EquipmentId
                        join stat in _equipmentStatisticsRepository.GetEntityAlls() on es.EquipmentId equals stat.EquipmentId
                        select new
                        {
                            ue.UnitName,
                            es.EquipmentName,       // 从 T_EquipmentDataStatistics 获取 EquipmentName
                            es.EquipmentCategory,   // 从 T_EquipmentDataStatistics 获取 EquipmentCategory
                            ue.Quantity,
                            stat.StatisticsDate     // 从 T_EquipmentStatistics 获取 StatisticsDate
                        };


            // 根据日期进行筛选
            if (startDate.HasValue)
            {
                query = query.Where(x => x.StatisticsDate >= startDate.Value.Date);  // 筛选大于等于起始日期
            }

            if (endDate.HasValue)
            {
                query = query.Where(x => x.StatisticsDate <= endDate.Value.Date);  // 筛选小于等于结束日期
            }

            var equipmentData = query.ToList();

            // 统计每个装备的总数量
            var totalEquipmentQuantity = equipmentData.Sum(x => x.Quantity);

            // 分析每个装备的数量和占比
            var analysisResult = equipmentData
                .GroupBy(x => new { x.EquipmentName, x.EquipmentCategory })
                .Select(g => new EquipmentAnalysisDto
                {
                    EquipmentName = g.Key.EquipmentName,
                    EquipmentCategory = g.Key.EquipmentCategory,
                    TotalQuantity = g.Sum(x => x.Quantity),
                    Percentage = (g.Sum(x => x.Quantity) / (double)totalEquipmentQuantity * 100).ToString("F2") + "%",
                    StatisticsDate = g.Max(x => x.StatisticsDate).ToString("yyyy-MM-dd")  // 获取最大日期，格式化为 yyyy-MM-dd
                })
                .ToList();



            return analysisResult;
        }





    }
}
